<?php
namespace App\Http\Middleware;
use Tymon\JWTAuth\Facades\JWTAuth;
use Closure;
use App\Helpers\SuccessResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Constant;

class Rbac{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        try{
            $user = json_decode(json_encode(JWTAuth::parseToken()->authenticate()), true);
            if(!$user || 0 == count($user)){
                return SuccessResponse::handler('['.Constant::EC_ACCESS_DENIED.'] access denied1.');
            }else{
                $request_path = explode('?', $_SERVER['REQUEST_URI']);
                $request_path = $request_path[0];
                $request_path = explode('/', $request_path);
                $request_path = [$request_path[0], $request_path[1], $request_path[2], $request_path[3], $request_path[4]];
                $request_path = implode('/', $request_path);

                $node = DB::table('rbac_node')->where('node_path', '=', $request_path)->first();
                $node = json_decode(json_encode($node), true);
                if(0 == count($node)){
                    return SuccessResponse::handler('['.Constant::EC_ACCESS_DENIED.'] access denied2.');
                }else{
                    $role = DB::table('rbac_role')->where('id', '=', $user['role_id'])->first();
                    $role = json_decode(json_encode($role), true);
                    if(!in_array($node['id'], explode(',', $role['role_nodes']))){
                        return SuccessResponse::handler('['.Constant::EC_ACCESS_DENIED.'] access denied3.');
                    }else{
                        $response = $next($request);
                    }
                }
            }
        }catch(\Exception $e){
                return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
            return SuccessResponse::handler('['.Constant::EC_ACCESS_DENIED.'] access denied4.');
        }
        return $response;
    }
}
